package com.itlzb.blog.auth.service.impl;

import com.itlzb.blog.auth.entity.LoginUser;
import com.itlzb.blog.auth.entity.User;
import com.itlzb.blog.auth.mapper.UserLoginMapper;
import com.itlzb.blog.auth.redis.RedisCache;
import com.itlzb.blog.auth.service.LoginService;
import com.itlzb.blog.auth.utils.JwtUtil;
import com.itlzb.blog.common.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserLoginMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result login(User user) {
                // 认证的时候需要Authentication对象，所以需要一个Authentication的实现类，这里选择了UsernamePasswordAuthenticationToken
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());

        // AuthenticationManager authenticate方法进行认证。在SecurityConfig配置类中，我们将AuthenticationManager注入到容器中。
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证通过，authenticate里将包含principal属性，该属性的值就是LoginUser，
        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        // 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String id = loginUser.getUser().getId().toString();
        String jwt = jwtUtil.createJWT(id);
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);

        // 把完整的用户信息存入redis，userid作为key
        redisCache.setCacheObject("login:" + id, loginUser);
        return new Result(200, "登陆成功", map);
    }


    @Override
    public Result register(User user) {
//        先根据用户名查询是否存在
        User queryUser = userMapper.selectByUsername(user.getUsername());
//        不存在插入
        if(queryUser != null) {
            throw new RuntimeException("用户名或密码错误");
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setSex("未知");
        user.setPersonalIntroduction(null);
        user.setPhone(null);
        user.setEmail(null);
        user.setDeleted(0);
        user.setCreatedTime(new Date());
        user.setUpdateTime(new Date());
        if(userMapper.insert(user) != 1) {
            return Result.fail("注册失败！");
        }
        return Result.success("注册成功！");
    }

    @Override
    public Result logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();
        redisCache.deleteObject("login:"+userid);
        return new Result(200,"退出成功");
    }

}
